package com.yj.auto.core.web.system.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.FileKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;
import com.xiaoleilu.hutool.io.FileUtil;
import com.yj.auto.core.base.annotation.Controller;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.base.model.ResponseModel;
import com.yj.auto.core.jfinal.base.BaseController;
import com.yj.auto.core.web.system.model.Atta;
import com.yj.auto.core.web.system.service.AttaService;
import com.yj.auto.plugin.table.model.DataTables;
import com.yj.auto.utils.DateUtil;

/**
 * 系统附件表 管理
 * 
 * 描述：
 * 
 */
@Controller(viewPath = "system")
public class AttaController extends BaseController {
	private static final Log logger = Log.getLog(AttaController.class);

	private static final String RESOURCE_URI = "atta/index";
	private static final String INDEX_PAGE = "atta_index.html";
	private static final String SHOW_PAGE = "atta_show.html";

	AttaService attaSrv = null;

	public void index() {
		QueryModel query = new QueryModel();
		query.setStime(DateUtil.toDateStr(DateUtil.addDay(DateUtil.date(), -7)));
		setAttr("query", query);
		render(INDEX_PAGE);
	}

	public void list(QueryModel query) {
		DataTables<Atta> dt = getDataTable(query, attaSrv);
		renderJson(dt);
	}

	public void get() {
		Integer id = getParaToInt(0);
		Atta model = attaSrv.get(id);
		setAttr("model", model);
		render(SHOW_PAGE);
	}

	public boolean delete() {
		ResponseModel<String> res = _delete(attaSrv);
		return res.isSuccess();
	}

	// 自动清空所有无效文件
	public void clear() {
		attaSrv.deleteInvalidAttas();
		ResponseModel<String> res = new ResponseModel<String>(true);
		res.setMsg("自动清空所有无效文件" + (res.isSuccess() ? "成功" : "失败"));
		renderJson(res);
	}

	/**
	 * 上传附件，如果错误，直接抛出异常
	 */
	public void upload() {
		try {
			Date now = new Date();
			String dataType = getPara();
			String path = dataType + File.separator + DateKit.toStr(now, AttaService.PATH_BY_DATE_FMT);
			UploadFile uf = getFile(dataType + "_file", path);// 获得文件及设置其保存路径。input：默认的name；path:文件保存的路径，每月创建一个文件夹
			File file = uf.getFile();
			String name = uf.getOriginalFileName();
			// 数据库对象
			Atta model = new Atta();
			model.setName(name);
			model.setPath(path);
			String ext = FileKit.getFileExtension(name);
//			if (StrKit.notBlank(ext)) {
//				ext = ext.toLowerCase();
//			}
			model.setExt(ext);
			model.setSize(FileUtil.size(file));
			model.setMimeType(uf.getContentType());
			model.setUserId(getSuId());
			model.setCtime(now);
			model.setDataType(dataType);
			// model.setMd5();
			attaSrv.save(model);

			name = model.getId() + "." + model.getExt();
			path = path + File.separator + name;
			model.setPath(path);
			String rename = file.getParentFile().getAbsolutePath() + File.separator + name;
			file.renameTo(new File(rename));
			attaSrv.update(model);
			model.getUri();
			// 返回json对象
			ResponseModel<Atta> res = new ResponseModel<Atta>(true);
			res.setData(model);
			renderJson(res);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			throw e;
		}
	}

	public void download() {
		boolean success = true;
		String msg = "文件下载成功";
		Integer id = getParaToInt();
		try {
			Atta model = attaSrv.get(id);
			renderAtta(model);
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
			msg = "文件下载失败(" + id + ")：" + e.getMessage();
			ResponseModel<String> res = new ResponseModel<String>(success);
			res.setMsg(msg);
			renderJson(res);
		}
	}

	public void downfirst() {
		boolean success = true;
		String msg = "文件下载成功";
		String dataType = getPara(0);
		Integer dataId = getParaToInt(1);
		try {
			Atta model = attaSrv.getByData(dataType, dataId);
			renderAtta(model);
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
			msg = "文件下载失败(" + dataType + "-" + dataId + ")：" + e.getMessage();
			ResponseModel<String> res = new ResponseModel<String>(success);
			res.setMsg(msg);
			renderJson(res);
		}
	}

	private void renderAtta(Atta model) {
		if (null != model) {
			File file = new File(model.getAbsolutePath());
			renderFile(file, model.getName());
		}
	}

	public void files() {
		boolean success = true;
		String msg = "文件获取成功";
		List<Atta> list = null;
		String dataType = getPara(0);
		Integer dataId = getParaToInt(1);
		try {
			list = attaSrv.findByDatas(dataType, dataId);
			for (Atta att : list) {
				att.getUri();
			}
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
			msg = "文件获取失败(" + dataType + "-" + dataId + ")：" + e.getMessage();
		}
		ResponseModel<List<Atta>> res = new ResponseModel<List<Atta>>(success);
		res.setMsg(msg);
		res.setData(list);
		renderJson(res);
	}
}